#include "windows.h"
#include "stdio.h"
#include "stdafx.h"
class  CSerialPort
{
    public:
		enum FlowControl
		{
			NoFlowControl,
			CtsRtsFlowControl,
			CtsDtrFlowControl,
			DsrRtsFlowControl,
			DsrDtrFlowControl,
			XonXoffFlowControl
		};

		enum Parity
		{    
			NoParity = 0,
			OddParity = 1,
			EvenParity = 2,
			MarkParity = 3,
			SpaceParity = 4
		};
	enum StopBits
	{
		OneStopBit,
		OnePointFiveStopBits,
		TwoStopBits
	};
    public:
	CSerialPort();
	~CSerialPort();

    public:
		void Open(int nPort, DWORD dwBaud = 9600, Parity parity = NoParity, BYTE DataBits = 8, 
			StopBits stopBits = OneStopBit, FlowControl fc = NoFlowControl, BOOL bOverlapped = FALSE);
		void Open(LPCTSTR pszPort, DWORD dwBaud = 9600, Parity parity = NoParity, BYTE DataBits = 8, 
			StopBits stopBits = OneStopBit, FlowControl fc = NoFlowControl, BOOL bOverlapped = FALSE);
		void Close(){
			if (IsOpen())
			{
				//Close down the comms port
				BOOL bSuccess = CloseHandle(m_hComm);
				m_hComm = INVALID_HANDLE_VALUE;
				if (!bSuccess)
					printf("CSerialPort::Close, Failed to close up the comms port, Error:%d\n", GetLastError());

				//Free the event object we are using
				if (m_hEvent)
				{
					CloseHandle(m_hEvent);
					m_hEvent = NULL;
				}
			}
		};
        BOOL IsOpen() const 
		{ return m_hComm != INVALID_HANDLE_VALUE; }
	
		//Reading / Writing Methods
		DWORD Read(void* lpBuf, DWORD dwCount);
		void  Read(void* lpBuf, DWORD dwCount, OVERLAPPED& overlapped, DWORD* pBytesRead=NULL);
		void  ReadEx(void* lpBuf, DWORD dwCount);
		DWORD Write(const void* lpBuf, DWORD dwCount);
		void  Write(const void* lpBuf, DWORD dwCount, OVERLAPPED& overlapped, DWORD* pBytesWritten=NULL);
		void  WriteEx(const void* lpBuf, DWORD dwCount);
		void  TransmitChar(char cChar);
		void  GetOverlappedResult(OVERLAPPED& overlapped, DWORD& dwBytesTransferred, BOOL bWait);
		void  CancelIo();
		DWORD BytesWaiting();
		BOOL  DataWaiting(DWORD dwTimeout);

		//Configuration Methods
		void GetConfig(COMMCONFIG& config);
		 void GetDefaultConfig(int nPort, COMMCONFIG& config);
		void SetConfig(COMMCONFIG& Config);
		 void SetDefaultConfig(int nPort, COMMCONFIG& config);
        
	    void GetStatus(COMSTAT& stat);
		void GetState(DCB& dcb);
		void SetState(DCB& dcb);

		void SetMask(DWORD dwMask);
		void GetMask(DWORD& dwMask);
		  void WaitEvent(DWORD& dwMask);
        BOOL WaitEvent(DWORD& dwMask, OVERLAPPED& overlapped);
		//Timeouts
		void SetTimeouts(COMMTIMEOUTS& timeouts);
		void GetTimeouts(COMMTIMEOUTS& timeouts);
		void Set0Timeout();
		void Set0WriteTimeout();
		void Set0ReadTimeout();

     protected:
		 typedef BOOL (WINAPI CANCELIO)(HANDLE);
		 typedef CANCELIO* LPCANCELIO;
		 HANDLE m_hComm;
		 HANDLE m_hEvent;
		 HINSTANCE  m_hKernel32;    //Kernel32 handle
		 LPCANCELIO m_lpfnCancelIo; //CancelIO function pointer
         
};


